﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchemaMonitor.json
{
	public class CPost
	{
		private CNodeRoot _r;

		public CPost(CNodeRoot r)
		{
			_r = r;

		}

		public string Id { get { return _r.Id; } }
		public Guid Guid { get { return _r.Guid; } }
		public string Message { get { return _r.Message; } }
		public List<long> PhotoIds { get { return _r.PhotoIds; } }
		public DateTime Created { get { return _r.CreatedTime; } }

		private CFieldList F { get { return _r.Fields; } }




		public CChapterList Chapters { get { return CChapter.Cache.GetByNodeGuid(Guid); } }
		public CChapter GetOrCreate(CSection s)
		{
			var cc = Chapters.GetBySectionId(s.SectionId);
			if (cc.Count > 0)
				return cc[0];
			var c = new CChapter();
			c.ChapterName = Message;
			c.ChapterSectionId = s.SectionId;
			c.ChapterNodeGuid = this.Guid;
			c.Save();
			return c;
		}
		public CPhotoList Photos { get { return CPhoto.Cache.GetByIds(PhotoIds ?? new List<long>(0)); } }
		public void ReconcilePhotos()
		{
			foreach (var c in this.Chapters)
				foreach (var p in Photos)
				{
					var cpp = c.ChapterPictures.GetByPhotoMD5(p.Md5);
					if (cpp.Count == 0)
					{
						var cp = new CChapterPicture();
						cp.PictureChapterId = c.ChapterId;
						cp.PicturePhotoMD5 = p.Md5;
						cp.PictureSortOrder = Photos.IndexOf(p);
						cp.Save();
					}
				}
		}
	}
}
